package com.codesynapse.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CodeSearchService {

    private final ElasticsearchClient elasticsearchClient;
    private static final String CODE_INDEX = "code_index";

    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> searchCode(String query) throws IOException {
        SearchResponse<Map<String, Object>> response = elasticsearchClient.search(s -> s
                .index(CODE_INDEX)
                .query(q -> q
                        .multiMatch(m -> m
                                .query(query)
                                .fields("content", "filename", "language")
                        )
                ), (Class<Map<String, Object>>) (Class<?>) Map.class);

        return response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());
    }

    public void indexCode(String filename, String content, String language) throws IOException {
        Map<String, Object> document = Map.of(
                "filename", filename,
                "content", content,
                "language", language
        );

        elasticsearchClient.index(i -> i
                .index(CODE_INDEX)
                .document(document)
        );
    }
} 